﻿using RestSharp;
using mortal_ClipboardSharing_windows.model;
using mortal_ClipboardSharing_windows.utils;
using System;

namespace mortal_ClipboardSharing_windows
{
    // 用委托实现回调，其实也可以用接口来做回调，但是比较麻烦就没用，c#又不支持匿名内部类更麻烦
    public delegate void Callback<T>(T httpResult);

    public class Api
    {

        static RestClient client = new RestClient("http://127.0.0.1:8081/v1/");

        /// <summary>
        /// 保存文本
        /// </summary>
        /// <param name="text"></param>
        /// <param name="callback"></param>
        public static void AddText(string text, Callback<HttpResult<string>> callback)
        {
            //callback(new HttpResult<string>() { Code=1});

            var request = new RestRequest("text/add", Method.POST);
            //request.AddHeader("Content-Type", "application/json;charset=utf-8");
            request.AddParameter("data", text);
            request.AddParameter("uid", 0);

            // async with deserialization
            var asyncHandle = client.ExecuteAsync<HttpResult<string>>(request, response =>
            {
                Console.WriteLine(response.Data);
                callback(response.Data);
            });

        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="text"></param>
        /// <param name="callback"></param>
        public static void Register(string username, string password, string nickname, Callback<HttpResult<string>> callback)
        {
            var request = new RestRequest("user/register", Method.POST);
            request.AddParameter("username", username);
            request.AddParameter("password", password);
            request.AddParameter("nickname", nickname);

            // async with deserialization
            var asyncHandle = client.ExecuteAsync<HttpResult<string>>(request, response =>
            {
                Console.WriteLine(response.Data);
                callback(response.Data);
            });
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="text"></param>
        /// <param name="callback"></param>
        public static void Login(string username, string password, Callback<HttpResult<UserEntity>> callback)
        {
            var request = new RestRequest("user/login", Method.POST);
            request.AddParameter("username", username);
            request.AddParameter("password", password);
            //request.AddParameter("token", Globle.TOKEN);

            // async with deserialization
            var asyncHandle = client.ExecuteAsync<HttpResult<UserEntity>>(request, response =>
            {
                Console.WriteLine(response.Data);
                callback(response.Data);
            });
        }
    }
}
